
package com.hlkj.pay.app.merchant.ext.impl.heepay.handler;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.framework.http.template.OkHttpTemplate;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantAccessContext;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantAccessQueryContext;
import com.hlkj.pay.app.merchant.ext.impl.heepay.dto.HeePayAccessExtentDto;
import com.hlkj.pay.app.merchant.ext.impl.heepay.dto.HeePayConfig;
import com.hlkj.pay.dto.merchant.MerchantAccessDto;
import com.hlkj.pay.enums.MerchantEnum;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAccessInfoDO;
import com.hlkj.pay.infrastructure.model.pay.PayChannelRequestDO;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author HlpayTeam
 * @date 2024/10/16 9:10
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HeePayMerchantAccessInfoHandler extends HeePayMerchantCommonParamsHandle {

    private final HeePayMerchantParamsHandle heePayMerchantParamsHandle;

    private final OkHttpTemplate okHttpTemplate;

    /**
     *
     * @param channelMerchantAccessContext
     */
    public void merchantAccess(ChannelMerchantAccessContext channelMerchantAccessContext) {
        CommonResult<HeePayConfig> lakalaConfigCommonResult = heePayMerchantParamsHandle.heePayConfig(channelMerchantAccessContext.getProviderChannelConfig(),
                channelMerchantAccessContext.isTest());
        if (!lakalaConfigCommonResult.isSuccess()) {
            channelMerchantAccessContext.setProcessStatus(false);
            channelMerchantAccessContext.setRemark(lakalaConfigCommonResult.getMsg());
            return;
        }
        HeePayConfig heePayConfig = lakalaConfigCommonResult.getData();
        CommonResult<Void> paramsCheckResult = heePayMerchantParamsHandle.merchantApplyParamsCheck(channelMerchantAccessContext);
        if (!paramsCheckResult.isSuccess()) {
            channelMerchantAccessContext.setProcessStatus(false);
            channelMerchantAccessContext.setRemark(paramsCheckResult.getMsg());
            return;
        }
        heePayMerchantParamsHandle.addProcessFileId(channelMerchantAccessContext, heePayConfig);
        if (!channelMerchantAccessContext.isProcessStatus()) {
            return;
        }
        Map<String, Object> params = heePayMerchantParamsHandle.merchantApplyParams(channelMerchantAccessContext, heePayConfig);
        MerchantAccessDto merchantAccessDto = channelMerchantAccessContext.getMerchantAccessDto();
        CommonResult<Map<String, String>> commonResult;
        MerchantAccessInfoDO merchantAccessInfo = merchantAccessDto.getMerchantAccessInfo();
        try {
            PayChannelRequestDO payChannelRequestDO = channelMerchantAccessContext.getPayChannelRequestDO();
            if (payChannelRequestDO == null) {
                payChannelRequestDO = new PayChannelRequestDO();
            }
            if (StringUtils.isEmpty(merchantAccessInfo.getApplyNo())) {
                payChannelRequestDO.setRequestParams(JsonUtils.toJsonString(params));
                commonResult = commonRequest(params, "customer.entry.apply", heePayConfig, channelMerchantAccessContext.isTest(), channelMerchantAccessContext.getAsyncReturnUrl());
                payChannelRequestDO.setResponse(JsonUtils.toJsonString(commonResult));
                if (!commonResult.isSuccess()) {
                    channelMerchantAccessContext.setProcessStatus(false);
                    channelMerchantAccessContext.setRemark(commonResult.getMsg());
                    return;
                }
                Map<String, String> data = commonResult.getData();
                channelMerchantAccessContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.AUDIT);
                channelMerchantAccessContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.CHANNEL_APPROVE);
                merchantAccessInfo.setApplyNo(data.get("apply_no"));
            }
            else {
                params.put("apply_no", merchantAccessInfo.getApplyNo());
                payChannelRequestDO.setRequestParams(JsonUtils.toJsonString(params));
                commonResult = commonRequest(params, "customer.entry.modify", heePayConfig, channelMerchantAccessContext.isTest(),
                        channelMerchantAccessContext.getAsyncReturnUrl());
                payChannelRequestDO.setResponse(JsonUtils.toJsonString(commonResult));
                channelMerchantAccessContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.AUDIT);
                channelMerchantAccessContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.CHANNEL_APPROVE);
            }
            channelMerchantAccessContext.setPayChannelRequestDO(payChannelRequestDO);
        }
        catch (Exception e) {
            channelMerchantAccessContext.setProcessStatus(false);
            channelMerchantAccessContext.setRemark(e.getMessage());
        }
    }

    /**
     * 进件查询
     *
     * @param channelMerchantAccessQueryContext
     */
    public void accessQueryRequest(ChannelMerchantAccessQueryContext channelMerchantAccessQueryContext) {
        CommonResult<HeePayConfig> lakalaConfigCommonResult = heePayMerchantParamsHandle.heePayConfig(channelMerchantAccessQueryContext.getProviderChannelConfig(),
                channelMerchantAccessQueryContext.isTest());
        if (!lakalaConfigCommonResult.isSuccess()) {
            channelMerchantAccessQueryContext.setProcessStatus(false);
            channelMerchantAccessQueryContext.setRemark(lakalaConfigCommonResult.getMsg());
            return;
        }
        MerchantAccessInfoDO merchantAccessInfo = channelMerchantAccessQueryContext.getMerchantAccessInfo();
        HeePayConfig heePayConfig = lakalaConfigCommonResult.getData();
        Map<String, Object> params = new HashMap<>();
        params.put("apply_no", merchantAccessInfo.getApplyNo());
        try {
            CommonResult<Map<String, String>> commonResult = commonRequest(params, "customer.entry.query", heePayConfig, channelMerchantAccessQueryContext.isTest(), null);
            if (!commonResult.isSuccess()) {
                channelMerchantAccessQueryContext.setProcessStatus(false);
                channelMerchantAccessQueryContext.setRemark(commonResult.getMsg());
            }
            Map<String, String> resultData = commonResult.getData();
            // -2=入驻图片驳回,-1=入驻驳回,0=入驻待审核,1=入驻审核中,2=业务开通中,3=商户启用,4=补充材料
            switch (resultData.get("audit_status")) {
                case "-2":
                case "-1":
                    channelMerchantAccessQueryContext.setProcessStatus(false);
                    channelMerchantAccessQueryContext.setRemark(resultData.get("audit_desc"));
                    channelMerchantAccessQueryContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.APPROVE_REFUSE);
                    break;
                case "0":
                case "1":
                    channelMerchantAccessQueryContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.CHANNEL_APPROVE);
                    return;
                default:
                    if(StringUtils.hasText(resultData.get("heepay_id"))){
                        HeePayAccessExtentDto heePayAccessExtentDto = new HeePayAccessExtentDto();
                        heePayAccessExtentDto.setHeePayAccount(resultData.get("heepay_account"));
                        heePayAccessExtentDto.setWalletId(resultData.get("wallet_id"));
                        heePayAccessExtentDto.setHeePayId(resultData.get("heepay_id"));
                        heePayAccessExtentDto.setCustomerId(resultData.get("customer_id"));
                        merchantAccessInfo.setSubMchId(heePayAccessExtentDto.getHeePayId());
                        merchantAccessInfo.setExtendA(JsonUtils.toJsonString(heePayAccessExtentDto));
                        // 没有签约直接进入配置
                        channelMerchantAccessQueryContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.WAIT_SET);
                        channelMerchantAccessQueryContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.SUBMERINFO);
                    }else {
                        // 没有签约直接进入配置
                        channelMerchantAccessQueryContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.CHANNEL_APPROVE);
                    }
                    break;
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            channelMerchantAccessQueryContext.setProcessStatus(false);
            channelMerchantAccessQueryContext.setRemark(e.getMessage());
        }
    }

}
